<?php
namespace Home\Model;
use Think\Model;
/**
 * 权限规则model
 */
class AdminModel extends Model{

	/**
	 * 初始化
	 */
	public function __construct(){

	}

	/**
	 * 用户后台登录
	 */
	public function login($keycode){

		$post = I('post.');

		$M = M('Users');

		//验证TOKEN重复表单提交
		if($M->autoCheckToken($post)){

			//人机验证码
			$luosimao_config = C('LUOSIMAO_CONFIG');
			$machine = array(
				"url"=>"http://captcha.luosimao.com/api/site_verify",
				"data"=>array("api_key"=>$luosimao_config['manma_api_key'],"response"=>$post['luotest_response']),
			);

			$is_manma = $this->Manmachine($machine);

			if($is_manma['res'] == "success"){

				$password = $this->decryption($keycode,$post['password']);
				$where['username'] = array("eq",$post['username']);
				$where['password'] = array("eq",$password);

				$data = $M->where($where)->find();

				if (empty($data)) {

					$data['code'] = 401;
					$data['msg'] = "账号或密码错误";

				}else{

					//验证激活账号
					if($data['status'] == 2){

						$data['code'] = 403;
						$data['msg'] = "账户激活";

						$_SESSION['user']=array(
							'email'=>$data['email'],
						);

					}else if($data['status'] == 0){
						$data['code'] = 404;
						$data['msg'] = "该账号已被禁止登陆,请联系客户!";

					}else{

						$last_login_ip = D('Mate')->getIPaddress();

						$items = array(
							"last_login_ip"=>$last_login_ip,
							"last_login_time"=>date("Y-m-d H:i:s",time())
						);

						$map['id'] = array("eq",$data['id']);

						M("users")->where($map)->setField($items);

						$_SESSION['user']=array(
							'id'=>$data['id'],
							'username'=>$data['username'],
							'avatar'=>$data['avatar'],
							'session_start_time'=>time()
						);

						$data['code'] = 200;
						$data['msg'] = "登录成功、前往管理后台";

					}

				}

			}else{

				$data['code'] = 402;
				$data['msg'] = "机器验证码不正确";

			}

		}else{
			$data['code'] = 400;
			$data['msg'] = "表单重复提交";
		}

		return $data;

	}

	/**
	 * 解密
	 */
	public function decryption($keycode,$password){

		//解密
		$privateKey = $keycode;

		$iv = $keycode;

		//解密
		$encryptedData = base64_decode($password);

		$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $privateKey, $encryptedData, MCRYPT_MODE_CBC, $iv);

		$data = md5(md5(trim($decrypted))."Yumcms.org");

		return $data;
	}

	/**
	 * 人机验证
	 */
	public function Manmachine($machine){

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL,$machine['url']);

		curl_setopt($ch, CURLOPT_HTTP_VERSION  , CURL_HTTP_VERSION_1_0 );
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 8);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_USERPWD  , 'api:key-'.$machine['data']['api_key']);
		curl_setopt($ch, CURLOPT_HTTPAUTH , CURLAUTH_BASIC);

		curl_setopt($ch, CURLOPT_POST, TRUE);
		curl_setopt($ch, CURLOPT_POSTFIELDS,$machine['data']);

		$res = curl_exec( $ch );
		curl_close( $ch );

		return json_decode($res,true);

	}

	/**
	 * 验证注册用户信息
	 */
	public function validation(){

		$post = I('get.');

		//验证用户名
		if($post['field'] == 'username'){

			$where['username'] = array("eq",$post['value']);

			$username = M("users")->where($where)->getField("username");

			if(!empty($username)){
				$data['error'] = "-21";
				$data['msg'] = "此用户名已被使用，换一个吧";
			}else{
				$data['error'] = "0";
				$data['msg'] = "ok";
			}

		}else if($post['field'] == 'email'){

			$where['email'] = array("eq",$post['value']);

			$email = M("users")->where($where)->getField("email");

			if(!empty($email)){
				$data['error'] = "-22";
				$data['msg'] = "此邮箱已被使用，换一个吧";
			}else{
				$data['error'] = "0";
				$data['msg'] = "ok";
			}


		}

		return $data;

	}


	/**
	 * 用户注册
	 */
	public function register($keycode,$mail_template){

		$post = I('post.');

		$M = M('Users');

		//验证TOKEN重复表单提交
		if($M->autoCheckToken($post)){

			//人机验证码
			$luosimao_config = C('LUOSIMAO_CONFIG');
			$machine = array(
				"url"=>"http://captcha.luosimao.com/api/site_verify",
				"data"=>array("api_key"=>$luosimao_config['manma_api_key'],"response"=>$post['luotest_response']),
			);

			$is_manma = $this->Manmachine($machine);

			if($is_manma['res'] == "success"){

				$password = $this->decryption($keycode,$post['password']);

				$where['username'] = array("eq",$post['username']);
				$where['email'] = array("eq",$post['email']);
				$where['_logic'] = 'or';

				$data = $M->where($where)->find();

				if (!empty($data)) {
					$data['code'] = 401;
					$data['msg'] = "此用户名或邮箱已被使用，换一个吧";
				}else{

					//生成激活码
					$email_code = md5(md5($post['username']).date("s",time()));

					$items = array(
						"username"=>$post['username'],
						"password"=>$password,
						"avatar"=>"/Upload/avatar/user1.jpg",
						"email"=>$post['email'],
						"email_code"=>$email_code,
						"phone"=>$post['mobile'],
						"status"=>2,
						"register_time"=>date("Y-m-d H:i:s",time()),
					);

					$user_id = M("users")->data($items)->add();

					if(!empty($user_id)){

						//写入用户组
						$info = array(
							"uid"=>$user_id,
							"group_id"=>7,
						);

						M("auth_group_access")->data($info)->add();

						//邮件发送
						$link = 'http://'.$_SERVER['HTTP_HOST'].U('Home/Admin/activation',array($user_id=>$email_code));

						$content = preg_replace(array('/(__username__)/','/(__link__)/'),array($post['username'],$link),$mail_template);

						send_email($post['email'],"账户激活-Yuncms.org",$content);

						$_SESSION['user']=array(
							'email'=>$post['email'],
						);

						$data['code'] = 200;
						$data['msg'] = "ok";

					}else{
						$data['code'] = 403;
						$data['msg'] = "系统繁忙，请稍后重试!";
					}
				}

			}else{

				$data['code'] = 402;
				$data['msg'] = "机器验证码不正确";

			}

		}else{
			$data['code'] = 400;
			$data['msg'] = "表单重复提交";
		}

		return $data;


	}

	/**
	 * 激活账号
	 */
	public function activation(){

		preg_match('/activation\/([0-9]*)\/([0-9a-zA-z]*)\.html/is',$_SERVER['REQUEST_URI'],$link);

		$where['id'] = array("eq",$link[1]);

		$where['email_code'] = array("eq",$link[2]);

		$status = M("users")->where($where)->getField("status");

		//未激活状态
		if($status == 2){

			M("users")-> where($where)->setField("status",1);

			$user_info = M("users")->field("avatar,username,status,id")->where($where)->find();

			if($user_info['status'] == 1){

				$_SESSION['user']=array(
					'id'=>$user_info['id'],
					'username'=>$user_info['username'],
					'avatar'=>$user_info['avatar']
				);


				$data['code'] = 200;
				$data['msg'] = "恭喜！您的账户激活成功！";

			}else{
				$data['code'] = 401;
				$data['msg'] = "验证失败！";
			}

		}else{
			$data['code'] = 400;
			$data['msg'] = "验证失败！";

		}

		return $data;

	}

	/**
	 * 激活邮件发送
	 */
	public function send_mail($mail_template){

		$email = session('user.email');

		$where['email'] = array("eq",$email);

		$items = M("users")->field("id,email_code,username,email")->where($where)->find();

		if(!empty($items)){

			//邮件发送
			$link = 'http://'.$_SERVER['HTTP_HOST'].U('Home/Admin/activation',array($items['id']=>$items['email_code']));

			$content = preg_replace(array('/(__username__)/','/(__link__)/'),array($items['username'],$link),$mail_template);

			send_email($items['email'],"账户激活-Yuncms.org",$content);

			$data['error'] = 0;
			$data['msg'] = "ok";
		}else{

			$data['error'] = -2;
			$data['msg'] = "系统繁忙，请稍后重试!";
		}

		return $data;

	}

	/**
	 * 忘记密码
	 */
	public function forgot_password($password_template){

		$email = I('post.email');

		$where['email'] = array("eq",$email);

		$items = M("users")->field("id,username,email,email_code")->where($where)->find();

		if(!empty($items)){

			//邮件发送
			$link = 'http://'.$_SERVER['HTTP_HOST'].U('Home/Admin/rebuild_password',array($items['id']=>$items['email_code']));

			$content = preg_replace(array('/(__username__)/','/(__link__)/'),array($items['username'],$link),$password_template);

			send_email($items['email'],"密码找回-Yuncms.org",$content);

			$_SESSION['user']=array(
				'email'=>$email,
			);

			$rule = "/([a-z0-9]*[-_]?[a-z0-9]+)+[\.][a-z]{2,3}([\.][a-z]{2})?$/i";

			preg_match($rule,$items['email'],$return);

			$links = "mail.".$return[0];

			$data = array(
				"code"=>200,
				"msg"=>"ok",
				"email"=>$items['email'],
				"links"=>$links
			);

		}else{
			$data = array(
				"code"=>400,
				"msg"=>"出错啦！"
			);
		}

		return $data;

	}

	/**
	 * 重新发送找回密码
	 */
	public function reset_password($password_template){

		$email = session('user.email');

		$where['email'] = array("eq",$email);

		$items = M("users")->field("id,email_code,username,email")->where($where)->find();

		if(!empty($items)){

			//邮件发送
			$link = 'http://'.$_SERVER['HTTP_HOST'].U('Home/Admin/rebuild_password',array($items['id']=>$items['email_code']));

			$content = preg_replace(array('/(__username__)/','/(__link__)/'),array($items['username'],$link),$password_template);

			send_email($items['email'],"密码找回-Yuncms.org",$content);

			$data['error'] = 0;
			$data['msg'] = "ok";
		}else{

			$data['error'] = -2;
			$data['msg'] = "系统繁忙，请稍后重试!";
		}

		return $data;

	}

	/**
	 * 重设密码
	 */
	public function rebuild_password($keycode){

		$post = I("post.");

		$M = M('Users');

		//验证TOKEN重复表单提交
		if($M->autoCheckToken($post)){

			$where['id'] = array("eq",$post['user_id']);
			$where['email_code'] = array("eq",$post['key']);
			$user_info = $M->where($where)->find();

			if(!empty($user_info)){

				//生成激活码
				$email_code = md5(md5($user_info['username']).date("s",time()));
				$password = $this->decryption($keycode,$post['password']);

				$list = array(
					"email_code"=>$email_code,
					"password"=>$password
				);

				M("users")->where($where)->setField($list);

				$data['code'] = 200;
				$data['msg'] = "OK";

			}else{

				$data['code'] = 401;
				$data['msg'] = "链接已经失效，请重新找回";
			}

		}else{
			$data['code'] = 400;
			$data['msg'] = "表单重复提交";
		}

		return $data;


	}

	/**
	 * 修改邮箱
	 */
	public function confirm_email(){

		preg_match('/confirm_email\/([0-9]*)\/([0-9a-zA-z]*)\.html/is',$_SERVER['REQUEST_URI'],$link);

		$where['id'] = array("eq",$link[1]);

		$where['email_code'] = array("eq",$link[2]);

		$user_info = M("users")->field('id,username,email_code,email_new,avatar')->where($where)->find();

		if(!empty($user_info['email_new'])){

			//生成激活码
			$email_code = md5(md5($user_info['username']).date("s",time()));

			$items = array("email"=>$user_info['email_new'],"email_code"=>$email_code,"email_new"=>"");

			M("users")->where($where)->setField($items);

			$_SESSION['user']=array(
				'id'=>$user_info['id'],
				'username'=>$user_info['username'],
				'avatar'=>$user_info['avatar']
			);

			$data['code'] = 200;
			$data['msg'] = "OK";

		}else{

			$data['code'] = 400;
			$data['msg'] = "系统繁忙，请稍后重试!";
		}

		return $data;


	}


}
